package com.cloudOffice.service.Impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudOffice.constant.GlobalConstant;
import com.cloudOffice.mapper.OaProcessTemplateMapper;
import com.cloudOffice.model.process.ProcessTemplate;
import com.cloudOffice.model.process.ProcessType;
import com.cloudOffice.service.OaProcessService;
import com.cloudOffice.service.OaProcessTemplateService;
import com.cloudOffice.service.OaProcessTypeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * 审批模板
 */
@Slf4j
@Service
public class OaProcessTemplateServiceImpl extends ServiceImpl<OaProcessTemplateMapper, ProcessTemplate> implements OaProcessTemplateService {
	
	@Resource
	private OaProcessTypeService processTypeService;
	@Resource
	private OaProcessService processService;
	
	//分页查询审批模板，把审批类型对应名称查询
	@Override
	public IPage<ProcessTemplate> selectPageProcessTempate(Page<ProcessTemplate> pageParam) {
		// 调用mapper的方法实现分页查询
		Page<ProcessTemplate> processTemplatePage = page(pageParam, null);
		List<ProcessTemplate> processTemplateList = processTemplatePage.getRecords();
		
		// 遍历list集合，得到每个对象的审批类型id
		for (ProcessTemplate processTemplate : processTemplateList) {
			ProcessType processType =
					processTypeService.getOne(Wrappers.<ProcessType>lambdaQuery().eq(ProcessType::getId,
					processTemplate.getProcessTypeId()));
			if (processType == null) {
				continue;
			}
			// 完成最终封装processTypeName
			processTemplate.setProcessTypeName(processType.getName());
		}
		return processTemplatePage;
	}
	
	//修改模板发布状态 1 已经发布
	//流程定义部署
	@Override
	public void publish(Long id) {
		//修改模板发布状态 1 已经发布
		ProcessTemplate processTemplate = getById(id);
		processTemplate.setStatus(GlobalConstant.INTEGER_ONE);
		updateById(processTemplate);
		
		//流程定义部署
		if (!StringUtils.isEmpty(processTemplate.getProcessDefinitionPath())) {
			try {
				processService.deployByZip(processTemplate.getProcessDefinitionPath());
			} catch (IOException e) {
				log.error("修改模版状态失败", e);
				throw new RuntimeException(e);
			}
		}
	}
	
}
